package qianmo.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import qianmo.common.log.annotation.Log;
import qianmo.common.log.enums.BusinessType;
import qianmo.common.security.annotation.RequiresPermissions;
import qianmo.system.domain.vo.CommentWhitChild;
import qianmo.system.domain.Comments;
import qianmo.system.service.ICommentsService;
import qianmo.common.core.web.controller.BaseController;
import qianmo.common.core.web.domain.AjaxResult;
import qianmo.common.core.utils.poi.ExcelUtil;
import qianmo.common.core.web.page.TableDataInfo;

/**
 * 评论Controller
 * 
 * @author qianmo
 * @date 2025-03-26
 */
@RestController
@RequestMapping("/comments")
public class CommentsController extends BaseController
{
    @Autowired
    private ICommentsService commentsService;

    /**
     * 查询评论列表
     */
    @RequiresPermissions("system:comments:list")
    @GetMapping("/list")
    public TableDataInfo list(Comments comments)
    {
        startPage();
        List<Comments> list = commentsService.selectCommentsList(comments);
        return getDataTable(list);
    }

    /**
     * 导出评论列表
     */
    @RequiresPermissions("system:comments:export")
    @Log(title = "评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Comments comments)
    {
        List<Comments> list = commentsService.selectCommentsList(comments);
        ExcelUtil<Comments> util = new ExcelUtil<Comments>(Comments.class);
        util.exportExcel(response, list, "评论数据");
    }

    /**
     * 获取评论详细信息
     */
    @RequiresPermissions("system:comments:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(commentsService.selectCommentsById(id));
    }

    /**
     * 新增评论
     */
    @RequiresPermissions("system:comments:add")
    @Log(title = "评论", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Comments comments)
    {
        return toAjax(commentsService.insertComments(comments));
    }

    /**
     * 修改评论
     */
    @RequiresPermissions("system:comments:edit")
    @Log(title = "评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Comments comments)
    {
        return toAjax(commentsService.updateComments(comments));
    }

    /**
     * 删除评论
     */
    @RequiresPermissions("system:comments:remove")
    @Log(title = "评论", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(commentsService.deleteCommentsByIds(ids));
    }

    @GetMapping("/question/{questionId}")
    public AjaxResult getCommentsByQuestionId(@PathVariable Long questionId) {
        List<Comments> comments = commentsService.getCommentsByQuestionId(questionId);
        List<CommentWhitChild> childList = new ArrayList<>();
        for (Comments comment : comments) {
            CommentWhitChild child = new CommentWhitChild();
            BeanUtils.copyProperties(comment, child);
            childList.add(child);
        }
        System.out.println("childList == " + childList);
        List<CommentWhitChild> commentWhitChildren = buildCommentTree(childList);
        System.out.println(commentWhitChildren);
        return success(commentWhitChildren);
    }

    public static List<CommentWhitChild> buildCommentTree(List<CommentWhitChild> comments) {
        Map<Long, CommentWhitChild> commentMap = new HashMap<>();
        List<CommentWhitChild> rootComments = new ArrayList<>();

        // 将所有评论放入 map 中，便于后续查找
        for (CommentWhitChild comment : comments) {
            commentMap.put(comment.getId(), comment);
        }

        System.out.println("commentMap == " + commentMap);

        // 遍历所有评论，构建父子关系
        for (CommentWhitChild comment : comments) {
            if (comment.getParentId() == null) {
                // 如果没有父评论，则为根评论
                rootComments.add(comment);
            } else {
                // 如果有父评论，则找到父评论并添加到其子评论列表中
                CommentWhitChild parentComment = commentMap.get(comment.getParentId());
                if (parentComment != null) {
                    if (parentComment.getChildList() == null) {
                        parentComment.setChildList(new ArrayList<>());
                    }
                    parentComment.getChildList().add(comment);
                }
            }
        }

        return rootComments;
    }

}
